package jms;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;


import outils.PropertyLoader;

public class MetierProduceur implements Runnable {
	
	private PropertyLoader pl = null;
	private QueueConnectionFactory factory = null;
	private QueueConnection connection = null;
	private Queue queue = null;
	private QueueSession session = null;
	private QueueSender sender = null;
	private static final Logger logger = Logger.getLogger("MetierProduceur");
	private Boolean running = null;
	private static final int DELAY = 5000;
	private static MetierProduceur instance  = null;
	
	private MetierProduceur(String propertiesFile) throws JMSException
	{
		pl = new PropertyLoader(propertiesFile);
				try {
			logger.setLevel(Level.ALL);
			this.logger.addHandler(new FileHandler(pl.getString("metier.logfile"), true));
		} catch (SecurityException e1) {
		
			e1.printStackTrace();
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
		factory = new ActiveMQConnectionFactory(pl.getString("url"));
		connection = factory.createQueueConnection();
		session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
		queue = session.createQueue(pl.getString("metier.output"));
		sender = session.createSender(queue);
		Thread thread = new Thread(this);
		running = true;
		thread.start();
	
	}
	
	public static MetierProduceur getInstance(String propertiesFile) {
		if (instance == null)
		{
			try {
				instance = new MetierProduceur(propertiesFile);
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return instance;
	}
	public void sendMessage(String xml) throws JMSException
	{
		
		TextMessage tm = session.createTextMessage(xml);
		sender.send(tm);
		
	}

	@Override
	public void run() {
		while(running)
		{
			try {
				Thread.sleep(DELAY);
			} catch (InterruptedException e) {
			
				e.printStackTrace();
			}
		}
		
	}
	
	public void setRunning(Boolean running) {
		this.running = running;
	}
}
